package com.example.compents.iec.iec104.server.handler;


import com.example.compents.iec.iec104.common.Iec104Constant;
import com.example.compents.iec.iec104.message.MessageDetail;
import com.example.compents.iec.util.ByteUtil;
import com.example.compents.masterMem;
import com.influxdb.client.InfluxDBClient;
import com.influxdb.client.InfluxDBClientFactory;
import com.influxdb.client.WriteApi;
import com.influxdb.client.domain.WritePrecision;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.ReferenceCountUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.time.Instant;

/**
 * 
* @ClassName: Check104Handler  
* @Description: 检查104报文 
* @author YDL 
* @date  
 */
public class Check104Handler extends ChannelInboundHandlerAdapter {
	
	private static final Logger LOGGER = LoggerFactory.getLogger(ChannelInboundHandlerAdapter.class);
	
	/**
	 * 拦截系统消息
	 */
	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		ByteBuf result = (ByteBuf) msg;
		byte[] bytes = new byte[result.readableBytes()];
		result.readBytes(bytes);
		LOGGER.info("接收到的报文: " + ByteUtil.byteArrayToHexString(bytes));
		if (bytes.length < Iec104Constant.APCI_LENGTH || bytes[0] != Iec104Constant.HEAD_DATA) {
			LOGGER.error("报文无效");
			ReferenceCountUtil.release(result);
		} else {
			/*masterMem mem = new masterMem();
			mem.setHost("hostmaster");
			mem.setUse_p(123.3);
			mem.setContext1(ByteUtil.byteArrayToHexString(bytes));
			String info = ByteUtil.byteArrayToHexString(bytes);
			System.out.println(ByteUtil.byteArrayToHexString(bytes));
			mem.setTime(Instant.now());
			String token = "d_WkuBxj2Olq-0_wYj5hlyToVAKuPFuaXE3WyD_wh8qkd6eRrntHoRKzWhNK6IRT3gf1FQ-c3U61YqT7XyqYTg==";
			InfluxDBClient client = InfluxDBClientFactory.create("http://127.0.0.1:8086", token.toCharArray());
			try (WriteApi writeApi = client.getWriteApi()) {
				// 桶 组织，精度，度量
				writeApi.writeMeasurement("aass8", "zcc", WritePrecision.NS, mem);
				System.out.println("dfgdgfdfgdgdgdf");
			}*/
			result.writeBytes(bytes);
			ctx.fireChannelRead(msg);
		}
	}
}
